package com.mdnote.practice.binary_search;

/**
 * @author Rhythm-2019
 * @version 1.0
 * @date 2020/9/18
 * @description
 */
public class LeetCode74 {


    public static void main(String[] args) {
        LeetCode74 leetCode74 = new LeetCode74();
        int[][] matrix = {
                {1, 2, 3, 4, 5},
                {6, 7, 8, 9, 10},
                {11, 12, 13, 14, 15}
        };
        boolean b = leetCode74.searchMatrix(matrix, 10);
        System.out.println(b);
    }
    public boolean searchMatrix(int[][] matrix, int target) {

        if (matrix.length == 0) {
            return false;
        }
        return binarySearch(matrix, target);
    }

    private boolean binarySearch(int[][] matrix, int target) {

        int left = 0;
        int right = matrix.length * matrix[0].length - 1;

        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (matrix[mid / matrix[0].length][mid % matrix[0].length] == target) {
                return true;
            } else if (matrix[mid / matrix[0].length][mid % matrix[0].length] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return false;
    }
}
